#include "scan_thread.h"

QMutex* scan_thread::mutex;
QWaitCondition* scan_thread::wcd;
std::queue<std::pair<QString, int>>* scan_thread::q = nullptr;
std::deque<int>* scan_thread::rand_q = nullptr;
bool scan_thread::paused = false;
bool scan_thread::stopped = false;
void scan_thread::setRand_num(int newRand_num)
{
    rand_num = newRand_num;
}

void scan_thread::setMytask(const std::vector<std::pair<QString, int> > newMytask)
{
    mytask = newMytask;
}

void scan_thread::sc_pause()
{
    mutex->lock();
    paused=true;
    msleep(100);
    mutex->unlock();
}

void scan_thread::sc_preceed()
{
    mutex->lock();
    paused=false;
    msleep(100);
    mutex->unlock();
}

void scan_thread::sc_stop()
{
    mutex->lock();
    stopped=true;
    msleep(100);
    mutex->unlock();
}

void scan_thread::run()
{
    //mutex->lock();
    emit has_started();
    msleep(rand_num);
    //mutex->unlock();
    std::pair<std::pair<QString,int>,std::pair<QString,bool>>ans;
    for(std::pair<QString,int>now:mytask){
        msleep(rand_num>>1);
        if(paused){
            int ca=0;
            emit has_paused();
            while(paused){
                msleep(rand_num*(++ca));
                if(ca>3)ca=3;
            }
            emit has_started();
        }
        if(stopped){
            mutex->lock();
            emit has_stopped();
            msleep(rand_num);
            mutex->unlock();
            return;
        }
        //socket deal;
        msleep(rand_num);
        tcp_tool->connectToHost(now.first,now.second);
        if(tcp_tool->waitForConnected(1000)){
            ans={now,{"tcp",true}};
        }else ans={now,{"tcp",false}};
        tcp_tool->abort();
        msleep(rand_num);
        sc_cb(ans);
        msleep(rand_num>>1);
        if(paused){
            int ca=0;
            emit has_paused();
            while(paused){
                msleep(rand_num*(++ca));
                if(ca>3)ca=3;
            }
            emit has_started();
        }
        if(stopped){
            mutex->lock();
            emit has_stopped();
            msleep(rand_num);
            mutex->unlock();
            return;
        }
    }
    mutex->lock();
    emit has_stopped();
    msleep(rand_num);
    mutex->unlock();
}
